const axios = require('axios');

const BASE_URL = 'http://localhost:3838/api/auth';
let authToken = '';

// 测试配置
const testUser = {
  username: 'testuser',
  email: 'test@example.com',
  password: 'Password123'
};

// 辅助函数：打印响应
const printResponse = (title, response) => {
  console.log(`\n${'='.repeat(50)}`);
  console.log(`📋 ${title}`);
  console.log(`📊 状态码: ${response.status}`);
  console.log(`📄 响应数据:`, JSON.stringify(response.data, null, 2));
  console.log(`${'='.repeat(50)}\n`);
};

// 测试函数
const runTests = async () => {
  try {
    console.log('🚀 开始API测试...\n');

    // 1. 测试注册
    console.log('1️⃣ 测试用户注册...');
    const registerResponse = await axios.post(`${BASE_URL}/register`, testUser);
    printResponse('注册响应', registerResponse);
    
    if (registerResponse.data.success) {
      authToken = registerResponse.data.data.token;
    }

    // 2. 测试登录
    console.log('2️⃣ 测试用户登录...');
    const loginResponse = await axios.post(`${BASE_URL}/login`, {
      email: testUser.email,
      password: testUser.password
    });
    printResponse('登录响应', loginResponse);
    
    if (loginResponse.data.success) {
      authToken = loginResponse.data.data.token;
    }

    // 3. 测试获取用户信息
    console.log('3️⃣ 测试获取用户信息...');
    const meResponse = await axios.get(`${BASE_URL}/me`, {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    printResponse('获取用户信息响应', meResponse);

    // 4. 测试更新用户信息
    console.log('4️⃣ 测试更新用户信息...');
    const updateResponse = await axios.put(`${BASE_URL}/profile`, {
      username: 'updateduser',
      email: 'updated@example.com'
    }, {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    printResponse('更新用户信息响应', updateResponse);

    // 5. 测试修改密码
    console.log('5️⃣ 测试修改密码...');
    const changePasswordResponse = await axios.put(`${BASE_URL}/change-password`, {
      currentPassword: testUser.password,
      newPassword: 'NewPassword123'
    }, {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    printResponse('修改密码响应', changePasswordResponse);

    // 6. 测试健康检查
    console.log('6️⃣ 测试健康检查...');
    const healthResponse = await axios.get('http://localhost:3838/health');
    printResponse('健康检查响应', healthResponse);

    console.log('✅ 所有测试完成！');

  } catch (error) {
    console.error('❌ 测试失败:', error.response?.data || error.message);
  }
};

// 错误测试函数
const runErrorTests = async () => {
  try {
    console.log('\n🔍 开始错误测试...\n');

    // 1. 测试重复注册
    console.log('1️⃣ 测试重复注册...');
    try {
      await axios.post(`${BASE_URL}/register`, testUser);
    } catch (error) {
      printResponse('重复注册错误响应', error.response);
    }

    // 2. 测试无效登录
    console.log('2️⃣ 测试无效登录...');
    try {
      await axios.post(`${BASE_URL}/login`, {
        email: 'wrong@example.com',
        password: 'wrongpassword'
      });
    } catch (error) {
      printResponse('无效登录错误响应', error.response);
    }

    // 3. 测试无效token
    console.log('3️⃣ 测试无效token...');
    try {
      await axios.get(`${BASE_URL}/me`, {
        headers: { Authorization: 'Bearer invalid_token' }
      });
    } catch (error) {
      printResponse('无效token错误响应', error.response);
    }

    // 4. 测试无效输入
    console.log('4️⃣ 测试无效输入...');
    try {
      await axios.post(`${BASE_URL}/register`, {
        username: 'a', // 太短
        email: 'invalid-email', // 无效邮箱
        password: '123' // 太简单
      });
    } catch (error) {
      printResponse('无效输入错误响应', error.response);
    }

    console.log('✅ 所有错误测试完成！');

  } catch (error) {
    console.error('❌ 错误测试失败:', error.message);
  }
};

// 运行测试
const main = async () => {
  console.log('🎯 Node.js MySQL 认证系统 API 测试');
  console.log('📍 测试地址:', BASE_URL);
  console.log('⏰ 开始时间:', new Date().toLocaleString());
  
  await runTests();
  await runErrorTests();
  
  console.log('\n🎉 测试程序结束');
  console.log('⏰ 结束时间:', new Date().toLocaleString());
};

// 如果直接运行此文件
if (require.main === module) {
  main();
}

module.exports = { runTests, runErrorTests }; 